package com.cms.permission.view

import android.content.Context
import android.content.Intent
import androidx.core.app.ActivityCompat
import com.android.baselibrary.base.BaseActivity
import com.cms.permission.R
import com.cms.permission.databinding.ActivityMainPermissionBinding
import com.cms.permission.inter.PermissionListener
import com.cms.permission.utils.PermissionUtils

class PermissionView : BaseActivity<ActivityMainPermissionBinding>() {
    var requestCodeInt = 0
    var permissions :Array<String> ?= null
    override fun getLayoutId(): Int = R.layout.activity_permission_view

    override fun initView() {
        requestCodeInt =  intent.getIntExtra(REQUEST_CODE,0)
       permissions = intent.getStringArrayExtra(PERMISSION)
        if (permissions == null || requestCodeInt < 0 || permissionListener == null){
            this.finish()
            return
        }
        permissions?.let {
          if (PermissionUtils.hasPermissionRequest(this,*it))   {
              permissionListener?.permissionGranted()
              this.finish()
              return
          }
            ActivityCompat.requestPermissions(this, it,requestCodeInt)
        }
    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCodeInt == requestCode){
           if (PermissionUtils.requestPermissionSuccess(*grantResults)){
               permissionListener?.permissionGranted()
               this.finish()
               return
           }
            if (!PermissionUtils.shouldShowRequestPermissionRationale(this,*permissions)){
                permissionListener?.permissionDenied()
                this.finish()
                return
            }
            permissionListener?.permissionCancel()
            this.finish()
            return
        }
    }
    override fun finish() {
        super.finish()
        overridePendingTransition(0, 0)
    }

    override fun initListener() {

    }
    companion object{
        private const val PERMISSION = "permission"
        private const val REQUEST_CODE = "request_code"
        var permissionListener:PermissionListener?=null
        fun requestPermission(context: Context,permission:Array<String>,requestCode:Int,listener:PermissionListener){
            val intent = Intent(context,PermissionView::class.java)
            intent.putExtra(PERMISSION,permission)
            intent.putExtra(REQUEST_CODE,requestCode)
            context.startActivity(intent)
            this.permissionListener = listener
        }
    }

}